<template>
  <div class="container">
    <Breadcrumb :items="[$t('订单管理'), $t('订单对账')]" />
    
    <!-- 统计卡片 -->
    <a-row :gutter="16" style="margin-bottom: 16px">
      <a-col :span="6">
        <a-card class="statistic-card">
          <a-statistic
            :title="$t('订单总数')"
            :value="statistics.orderCount"
            :value-style="{ color: '#0084FF' }"
            show-group-separator
          >
            <template #suffix>
              <icon-file style="margin-left: 8px" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="statistic-card">
          <a-statistic
            :title="$t('充电总电量(kWh)')"
            :value="statistics.totalChargingElec"
            :precision="2"
            :value-style="{ color: '#00B42A' }"
            show-group-separator
          >
            <template #suffix>
              <icon-thunderbolt style="margin-left: 8px" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="statistic-card">
          <a-statistic
            :title="$t('已对账金额(元)')"
            :value="statistics.totalActualAmount"
            :precision="2"
            :value-style="{ color: '#FF7D00' }"
            show-group-separator
          >
            <template #suffix>
              <icon-money style="margin-left: 8px" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="statistic-card">
          <a-statistic
            :title="$t('未对账订单数')"
            :value="statistics.totalUnmatchCount"
            :value-style="{ color: '#F53F3F' }"
            show-group-separator
          >
            <template #suffix>
              <icon-exclamation-circle style="margin-left: 8px" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-card class="general-card">
      <template #title>
        {{ $t('订单对账管理') }}
      </template>
      
      <!-- 搜索表单 -->
      <div class="search-form-wrapper">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="searchForm"
              label-align="left"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
              label-layout="inline"
              class="search-form"
            >
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-item field="thirdPartyOrderNo" :label="$t('第三方订单号')" class="form-item">
                    <a-input v-model="searchForm.thirdPartyOrderNo" :placeholder="$t('请输入第三方订单号')" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="platformId" :label="$t('平台')" class="form-item">
                    <a-select
                      v-model="searchForm.platformId"
                      :placeholder="$t('请选择平台')"
                      allow-clear
                      allow-search
                    >
                      <a-option
                        v-for="item in platformOptions"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="stationId" :label="$t('站点')" class="form-item">
                    <a-select
                      v-model="searchForm.stationId"
                      :placeholder="$t('请选择站点')"
                      allow-clear
                      allow-search
                    >
                      <a-option
                        v-for="item in stationOptions"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.stationName }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-item field="thirdPileNo" :label="$t('三方设备编号')" class="form-item">
                    <a-input v-model="searchForm.thirdPileNo" :placeholder="$t('请输入三方充电桩编号')" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="timeRange" :label="$t('创建时间')" class="form-item">
                    <a-range-picker
                      v-model="timeRange"
                      style="width: 100%"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <div class="form-actions">
                <a-space>
                  <a-button type="primary" @click="handleSearch" class="search-btn">
                    <template #icon><icon-search /></template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="handleReset" class="reset-btn">
                    <template #icon><icon-refresh /></template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </div>
            </a-form>
          </a-col>
        </a-row>
      </div>

      <!-- 操作按钮 -->
      <div class="operation-wrapper">
        <a-space>
          <a-button type="primary" class="operation-btn" @click="handleExport">
            <template #icon><icon-download /></template>
            {{ $t('导出') }}
          </a-button>
          <a-button type="primary" status="success" class="operation-btn" @click="handleSync">
            <template #icon><icon-sync /></template>
            {{ $t('同步') }}
          </a-button>
        </a-space>
      </div>

      <!-- 同步状态 Tabs -->
      <a-tabs v-model:active-key="activeTab" @tab-click="handleTabChange">
        <a-tab-pane key="0" :title="$t('未同步')">
          <OrderTable :data="tableData" :loading="loading" :pagination="pagination" @page-change="onPageChange" />
        </a-tab-pane>
        <a-tab-pane key="1" :title="$t('已同步')">
          <OrderTable :data="tableData" :loading="loading" :pagination="pagination" @page-change="onPageChange" />
        </a-tab-pane>
        <a-tab-pane key="2" :title="$t('异常')">
          <OrderTable :data="tableData" :loading="loading" :pagination="pagination" @page-change="onPageChange" />
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import OrderTable from './components/order-table.vue';
import { getOrderList, getOrderStatistics } from '@/api/order/reconciliation';
import type { ChargingOrder, ChargingOrderStatisticVO } from '@/api/order/reconciliation/types';
import axios from 'axios';

// 定义平台和站点接口
interface Platform {
  id: number;
  name: string;
}

interface Station {
  id: number;
  stationName: string;
}

// 加载状态
const { loading, setLoading } = useLoading();

// 搜索表单数据
const searchForm = reactive({
  thirdPartyOrderNo: '',
  platformId: undefined as number | undefined,
  stationId: undefined as number | undefined,
  thirdPileNo: '',
  current: 1,
  size: 10
});

// 时间范围
const timeRange = ref<string[]>([]);

// Tab 激活key
const activeTab = ref('0');

// 表格数据
const tableData = ref<ChargingOrder[]>([]);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
});

// 平台选项
const platformOptions = ref<Platform[]>([]);

// 站点选项
const stationOptions = ref<Station[]>([]);

// 统计数据
const statistics = ref<ChargingOrderStatisticVO>({
  orderCount: 0,
  totalChargingElec: 0,
  totalActualAmount: 0,
  totalUnmatchCount: 0
});

// 获取平台列表
async function fetchPlatformList() {
  try {
    const res = await axios.get('/api/platform/list');
    if (res.data && Array.isArray(res.data)) {
      platformOptions.value = res.data.map((item: { id: number; platformName?: string; name?: string }) => ({
        id: item.id,
        name: item.platformName || item.name || '未知平台'
      }));
    }
  } catch (error) {
    console.error('获取平台列表失败:', error);
    Message.error('获取平台列表失败');
  }
}

// 获取站点列表
async function fetchStationList() {
  try {
    const res = await axios.get('/api/car/station/list');
    if (res.data && Array.isArray(res.data)) {
      stationOptions.value = res.data.map((item: { id: number; stationName?: string; name?: string }) => ({
        id: item.id,
        stationName: item.stationName || item.name || '未知站点'
      }));
    }
  } catch (error) {
    console.error('获取站点列表失败:', error);
    Message.error('获取站点列表失败');
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const params = {
      ...searchForm,
      syncStatus: Number(activeTab.value),
      startTime: timeRange.value?.[0],
      endTime: timeRange.value?.[1]
    };
    const res = await getOrderStatistics(params);
    statistics.value = res.data;
  } catch (error) {
    console.error('获取统计数据失败:', error);
    Message.error('获取统计数据失败');
  }
};

// 搜索处理
const handleSearch = async () => {
  try {
    setLoading(true);
    const params = {
      ...searchForm,
      syncStatus: Number(activeTab.value),
      startTime: timeRange.value?.[0],
      endTime: timeRange.value?.[1]
    };
    const [listRes] = await Promise.all([
      getOrderList(params),
      fetchStatistics()
    ]);
    tableData.value = listRes.data.records;
    pagination.total = listRes.data.total;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    Message.error('获取订单列表失败');
  } finally {
    setLoading(false);
  }
};

// 重置处理
const handleReset = () => {
  const resetForm = {
    thirdPartyOrderNo: '',
    platformId: undefined,
    stationId: undefined,
    thirdPileNo: '',
    current: 1,
    size: 10
  };
  Object.assign(searchForm, resetForm);
  timeRange.value = [];
  handleSearch();
};

// Tab切换处理
const handleTabChange = () => {
  pagination.current = 1;
  handleSearch();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  handleSearch();
};

// 导出处理
const handleExport = async () => {
  try {
    setLoading(true);
    const params = {
      ...searchForm,
      syncStatus: Number(activeTab.value),
      startTime: timeRange.value?.[0],
      endTime: timeRange.value?.[1]
    };
    // TODO: 调用导出API
    Message.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    Message.error('导出失败');
  } finally {
    setLoading(false);
  }
};

// 同步处理
const handleSync = async () => {
  try {
    setLoading(true);
    // TODO: 调用同步API
    Message.success('同步成功');
    handleSearch();
  } catch (error) {
    console.error('同步失败:', error);
    Message.error('同步失败');
  } finally {
    setLoading(false);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  fetchPlatformList();
  fetchStationList();
  handleSearch();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.statistic-card {
  padding: 20px;
  border-radius: 4px;
  :deep(.arco-statistic-title) {
    font-size: 14px;
    font-weight: bold;
  }
  :deep(.arco-statistic-value) {
    font-size: 24px;
    font-weight: bold;
  }
}

.general-card {
  :deep(.arco-card-header) {
    padding: 20px;
  }
  :deep(.arco-card-body) {
    padding: 0 20px 20px 20px;
  }
}

.search-form-wrapper {
  background-color: var(--color-fill-2);
  padding: 24px;
  border-radius: 4px;
  margin-bottom: 16px;

  :deep(.arco-form-item) {
    margin-bottom: 16px;

    .arco-form-item-label-col {
      padding-right: 12px;
    }

    .arco-form-item-wrapper {
      width: 100%;
    }

    .arco-input-wrapper,
    .arco-select-view,
    .arco-picker {
      background-color: var(--color-bg-2);
      border: 1px solid var(--color-border-2);
      border-radius: 4px;
      transition: all 0.2s ease-in-out;

      &:hover {
        border-color: rgb(var(--primary-6));
        background-color: var(--color-bg-1);
      }

      &.arco-input-focus,
      &.arco-select-focus,
      &.arco-picker-focus {
        border-color: rgb(var(--primary-6));
        box-shadow: 0 0 0 2px rgba(var(--primary-6), 0.1);
        background-color: var(--color-bg-1);
      }
    }
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--color-border-2);

  .arco-btn {
    min-width: 100px;
    margin: 0 8px;
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.2s ease-in-out;

    &:hover {
      transform: translateY(-1px);
    }

    &.arco-btn-primary {
      &:hover {
        background-color: rgb(var(--primary-7));
        box-shadow: 0 4px 12px rgba(var(--primary-6), 0.2);
      }
    }
  }
}

.operation-wrapper {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;

  .arco-btn {
    min-width: 90px;
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.2s ease-in-out;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(var(--primary-6), 0.1);
    }
  }
}
</style> 